#!/usr/bin/env python
# -*- coding: utf-8 -*-

from utils import log

from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy import Table, MetaData, Column, Integer,  Unicode, TIMESTAMP, func
from controls.data_pool_mysql import engine

metadata = MetaData()
Session = sessionmaker()
Session.configure(bind=engine)

"""System Message Status collection has
    id:             自增id（int）
    userid:         系统消息接收者id（int）
    messageid:      系统消息id（int）
    status:         系统消息状态（int）     1：正常消息 2：已删除消息
    ctime:          创建时间（datetime）
"""

class SystemMessageStatusItem(object):

    def to_dict(self):
        res = {}
        res['userid'] = self.userid
        res['messageid'] = self.messageid
        res['status'] = self.status
        res['ctime'] = self.ctime.strftime("%Y-%m-%d %H:%M:%S")\
            if self.ctime else ""
        return res

    def __repr__(self):
        return "%d" % (self.userid)

system_message_status_table = Table(
    'system_message_status', metadata,
    Column('id', Integer, primary_key=True, autoincrement=True),
    Column('userid', Integer, nullable=False),
    Column('messageid', Integer, nullable=False),
    Column('status', Integer, nullable=False),
    Column('ctime', TIMESTAMP, server_default=func.now())
)

mapper(SystemMessageStatusItem, system_message_status_table)

def create_system_message_status_table_if_not_exist():
    metadata.create_all(engine)

def add_system_message_status_item(p_item):
    item = SystemMessageStatusItem()
    item.userid = p_item['userid']
    item.messagid = p_item['messageid']
    item.status = p_item['status']

    try:
        session = Session()
        session.add(item)
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


def get_system_message_status_by_userid_status(p_userid, p_status):
    try:
        session = Session()
        items = session.query(SystemMessageStatusItem)\
            .filter_by(userid=p_userid).filter_by(status=p_status).all()
        res = [item.to_dict()['messageid'] for item in items]
        return res if res else []
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()

def add_system_message_status_item_by_item_list(p_item_list):
    try:
        session = Session()
        for item in p_item_list:
            session.add(item)
        session.flush()
        session.commit()
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()

def update_system_message_status_by_userid(p_userid, p_item):
    try:
        session = Session()
        session.query(SystemMessageStatusItem).filter_by(userid=p_userid).filter_by(status=1).update(p_item)
        session.flush()
        session.commit()
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()

if __name__ == '__main__':
    create_system_message_status_table_if_not_exist()